package com.hairline.type_handler;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hairline.bean.vo.CommentVO;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class CommitListVoHandler  extends BaseTypeHandler<List> {

    ObjectMapper objectMapper = new ObjectMapper();


    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int index, List list, JdbcType jdbcType) throws SQLException {

        String value = objectMapper.writeValueAsString(list);
        preparedStatement.setString(index,value);
    }

    @SneakyThrows
    @Override
    public List getNullableResult(ResultSet resultSet, String columnLabel) throws SQLException {
        String string = resultSet.getString(columnLabel);
        return parseResult(string);
    }
    @SneakyThrows
    @Override
    public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String string = resultSet.getString(i);

        return parseResult(string);
    }
    @SneakyThrows
    @Override
    public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String string = callableStatement.getString(i);
        return parseResult(string);
    }
    private List parseResult(String result) throws JsonProcessingException {
        return objectMapper.readValue(result,List.class);
    }
}
